import easygui as g
import pymysql
import matplotlib.pyplot as plt
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']#插入中文不会出现空格
import random

#得到所有的州的名称
states = {"U.S."}
list=[]
def get_state():  # 将所有的州写入全局变量中
    for line in open("all_cities.txt", "r"):  # 设置文件对象并读取每一行文件
        line = line[:-1]  # 去除换行符
        states.add(line.split("'")[1])  # 将每一行文件加入到state中,只有州的名称

def main():
    # 启动界面
    g.msgbox("\n\n\t\t\t\t美国大选的数据处理", ok_button='打开', title="美国大选的数据处理")
    #得到所有的州的名称
    get_state()
    reply = g.choicebox("选择的州", choices=states)
    #如果有选择则确认选择的州
    if reply!=None :
        YN=g.boolbox(msg='\n\n\n\t\t\t\t确定你的选择：'+reply, title='确认选择', choices=('Yes', 'No'), image=None)
        if YN==True:#完成了最终的确认
            sql="select clinton,trump,johnson,grade,id from tab where state='"+reply+"'"#构造sql语句查找数据
            db = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="4399", db="py_us_pre_ele",charset="utf8")#得到一个物理会话
            cur = db.cursor()#得到一个cursor对象
            cur.execute(sql)#执行sql语句
            for i in range(cur.rowcount - 1):#去除列名
                row = cur.fetchone()
                if 'a' not in row[0]:#防止列名
                    clinton = float(row[0].strip())
                    trump = float(row[1].strip())
                    johnson = float(row[2].strip())
                    tup = (clinton, trump, johnson)
                    list.append(tup)
                    paint(tup, reply, row[3], row[4])
                    con=g.buttonbox(reply + "州的第" + row[4] + "号" + "图片" + "评论机构评分;" + row[3], image=str(row[4]) + 'pie.png',
                                      choices=("下一张", "退出"))
                    if con=="退出":
                        exit("退出")
        else:
                g.msgbox("程序退出")

def paint(tup,state,grade,id):#画图
    label_list = ["川普", "希拉里", "强生", "弃权票"] # 各部分标签
    size = [tup[0], tup[1], tup[2], (100-tup[0]-tup[1]-tup[2])]  # 各部分大小
    color = ["red", "green", "blue", "yellow"]  # 各部分颜色
    explode = [0.05, 0, 0, 0]  # 各部分突出值
    patches, l_text, p_text = plt.pie(size, explode=explode, colors=color, labels=label_list, labeldistance=1.1,
                                      autopct="%1.1f%%", shadow=False, startangle=90, pctdistance=0.6)
    plt.axis("equal")  # 设置横轴和纵轴大小相等，这样饼才是圆的
    plt.legend()
    ran_num = random.sample(range(10000), 1)
    plt.savefig(str(id)+'pie.png')
    plt.show()

if __name__ == '__main__':
    main()



